#include <engine.h>
#include <defs.h>
#include <user.h>

void EngineTickNotifier() {
  // dependency check
  WhoIs("clock-server");

  engine_req msg;
  msg.type = MSG_TICK;

  int server_tid;
  Receive(&server_tid, NULL, 0);
  Reply(server_tid, NULL, 0);

  for ( ; ; ) {
    Delay(1);
    Send(server_tid, (char*)&msg, sizeof(engine_req), NULL, 0);
  }
}

// TODO: this currently hardcodes velocity for Train 40 in cm/s. We will need
// to make it more general for TC2 and the final project.
void EngineServer() {
  
  // dependency check
  WhoIs("terminal-tx-server");  // need this to print
  
  // train velocities
  float vel_table[15];
  vel_table[0] = 0.0;
  vel_table[1] = 3.685097426205;
  vel_table[2] = 7.37019485241;
  vel_table[3] = 12.3734107199;
  vel_table[4] = 17.8114927858;
  vel_table[5] = 22.0956451512;
  vel_table[6] = 26.7861996851;
  vel_table[7] = 31.0869684794;
  vel_table[8] = 35.6688526759;
  vel_table[9] = 39.9339896184;
  vel_table[10] = 44.1991265609;
  vel_table[11] = 48.1123734173;
  vel_table[12] = 52.0310660871;
  vel_table[13] = 54.9470777822;
  vel_table[14] = 61.0594750044;

  // TODO: add acceleration
  
  // current state
  sensor last;
  int speed;  // train speed number (0-14)
  float vel;  // velocity in cm/s
  float pos;  // position from last in cm
  int known = FALSE;
  engine_req msg;
  
  // create tick notifier
  int tick_notifier_tid = Create(5, &EngineTickNotifier, "EngineTickNotifier");
  Send(tick_notifier_tid, NULL, 0, NULL, 0);

  // notify parent
  int parent_tid;
  Receive(&parent_tid, NULL, 0);
  Reply(parent_tid, NULL, 0);
  
  int sender_tid;
  for ( ; ; ) {
    Receive(&sender_tid, (char*)&msg, sizeof(engine_req));
    switch (msg.type) {
    case MSG_SPEED_UPDATE:
      speed = msg.speed;
      vel = vel_table[speed];
    case MSG_SENSOR_UPDATE:
      known = TRUE;
      pos = 0.0;
    case MSG_TICK:
      pos += vel;
      // TODO: update display
    }
  }
}
